// 创建Web Worker
export const createBookingWorker = (config) => {
  const workerCode = `
    let running = false;
    let retryCount = 0;

    // 处理消息
    self.onmessage = function(e) {
      const { type, data } = e.data;
      
      switch (type) {
        case 'start':
          running = true;
          startBooking(data);
          break;
        case 'stop':
          running = false;
          break;
      }
    };

    // 抢票逻辑
    function startBooking(config) {
      const {
        url,
        method = 'POST',
        headers = {},
        body = {},
        requestInterval,
        maxRetries,
        retryInterval,
        timeout
      } = config;

      function makeRequest() {
        if (!running) return;

        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), timeout);

        fetch(url, {
          method,
          headers: {
            'Content-Type': 'application/json',
            ...headers
          },
          body: JSON.stringify(body),
          signal: controller.signal
        })
        .then(response => {
          clearTimeout(timeoutId);
          if (response.ok) {
            return response.json();
          }
          throw new Error('HTTP error! status: ' + response.status);
        })
        .then(data => {
          self.postMessage({ type: 'success', data });
        })
        .catch(error => {
          clearTimeout(timeoutId);
          retryCount++;
          
          if (retryCount > maxRetries) {
            self.postMessage({ 
              type: 'error', 
              error: '已达到最大重试次数' 
            });
            return;
          }

          self.postMessage({ 
            type: 'retry', 
            data: { 
              count: retryCount, 
              error: error.message 
            } 
          });

          setTimeout(() => {
            if (running) {
              makeRequest();
            }
          }, retryInterval);
        });
      }

      // 开始第一次请求
      makeRequest();

      // 设置定时器进行下一次请求
      const intervalId = setInterval(() => {
        if (running) {
          makeRequest();
        } else {
          clearInterval(intervalId);
        }
      }, requestInterval);
    }
  `;

  const blob = new Blob([workerCode], { type: "application/javascript" });
  const workerUrl = URL.createObjectURL(blob);
  const worker = new Worker(workerUrl);

  // 清理URL
  URL.revokeObjectURL(workerUrl);

  return worker;
};

// 格式化请求配置
export const formatBookingConfig = (config) => {
  return {
    url: config.url,
    method: config.method || "POST",
    headers: config.headers || {},
    body: config.body || {},
    requestInterval: Math.max(100, config.requestInterval || 1000),
    maxRetries: Math.max(0, config.maxRetries || 3),
    retryInterval: Math.max(100, config.retryInterval || 1000),
    timeout: Math.max(1000, config.timeout || 5000),
  };
};

// 解析抢票结果
export const parseBookingResult = (result) => {
  try {
    if (typeof result === "string") {
      result = JSON.parse(result);
    }

    return {
      success: result.success || false,
      message: result.message || "未知错误",
      data: result.data || null,
      timestamp: new Date().toISOString(),
    };
  } catch (error) {
    return {
      success: false,
      message: "解析结果失败",
      data: null,
      timestamp: new Date().toISOString(),
    };
  }
};
